
/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.neo4j;

import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;

import com.tompai.neo4j.Neo4jNativeJavaAPI.MyLabels;
import com.tompai.neo4j.Neo4jNativeJavaAPI.MyRelationshipTypes;
import com.tompai.neo4j.batis.MybatisUtil;
import com.tompai.neo4j.dao.TwitterRelapMapper;
import com.tompai.neo4j.log.BaseLoger;
import com.tompai.neo4j.model.TwitterRelap;

/**
* @desc: neo4j-tools
* @name: TwitterRelapToNeo4j.java
* @author: tompai
* @createTime: 2018年12月30日 下午9:01:30
* @history:
* @version: v1.0
*/

public class TwitterLocalToNeo4j extends BaseLoger{

	private static String db_path="target/neo4j-twitter-db";
	
	/**
	 * Label类型枚举类
	 */
	enum MyLabels implements Label {
	    PERSONS, USERS
	}

	/**
	 * 关系类型枚举类
	 */
	enum MyRelationshipTypes implements RelationshipType {
	    FOLLOWERS, FOLLOWING
	}
	
	 private static void registerShutdownHook(final GraphDatabaseService graphDB) {
	        Runtime.getRuntime().addShutdownHook(
	                new Thread() {
	                    public void run() {
	                        //Shutdown the Database
	                        System.out.println("Server is shutting down");
	                        graphDB.shutdown();
	                    }
	                }
	        );
	    }
	
	/**
	* @author: tompai
	* @createTime: 2018年12月30日 下午9:01:30
	* @history:
	* @param args void
	*/

	public static void main(String[] args) {
		//TODO Auto-generated method stub

		TwitterRelapMapper twitterRelapMapper=MybatisUtil.getSession().getMapper(TwitterRelapMapper.class);
		//指定 Neo4j 存储路径
        File file = new File(db_path);
        //Create a new Object of Graph Database
        GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase(file);
        logger.info("Server is up and Running");
        TwitterRelap relap=new TwitterRelap();
        long index=1L;
        relap=twitterRelapMapper.selectById(index);
        long start=System.currentTimeMillis();  //当前的时间
        try(Transaction tx = graphDB.beginTx()){
        	do {
        		logger.info("Done id: {}",relap.getId());
        		Label label=MyLabels.USERS;
        		String valuea=relap.getAccounta();
        		Node node=graphDB.findNode(label, "name", valuea);
        		Node user1;
        		Node user2;
        		if(node==null) {
        			user1 = graphDB.createNode(MyLabels.USERS);
                    user1.setProperty("name", valuea);
        		}else {
        			user1=node;
        		}
        		node=null;
        		String valueb=relap.getAccountb();
        		node=graphDB.findNode(label, "name", valueb);
        		if(node==null) {
        			user2 = graphDB.createNode(MyLabels.USERS);
                    user2.setProperty("name", valueb);
        		}else {
        			user2=node;
        		}

        		//Create a unique constraint
        		/*graphDB.schema().constraintFor(MyLabels.USERS)
        				.assertPropertyIsUnique(valuea)
        				.create();*/
        		
                String role=relap.getRole();
                Relationship relationship = null;
                if(role.equals("followers")) {
                	relationship=user1.createRelationshipTo(user2,MyRelationshipTypes.FOLLOWERS);
                }else  if(role.equals("following")) {
                	relationship= user1.createRelationshipTo(user2,MyRelationshipTypes.FOLLOWING);
                }
                Date date=relap.getInputTime();
                String inTime=date.toString();
                relationship.setProperty("inputTime", inTime);
                tx.success();
                
                index++;
                relap=twitterRelapMapper.selectById(index);
    		} while (index<50000);//relap!=null
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	//关闭数据库
            graphDB.shutdown();    
        }
        long end=System.currentTimeMillis();  //当前的时间
        logger.info("Time Use: {} seconds" ,(end-start)/1000.0);
        //Register a Shutdown Hook
        registerShutdownHook(graphDB);
	} 

}

